package com.ruge.core.tool;

import com.ruge.core.exception.BaseBusinessException;
import com.ruge.core.exception.IError;
import com.ruge.core.response.Response;
import com.ruge.tool.json.JsonTool;
import com.ruge.tool.map.MapTool;
import com.ruge.tool.str.StringTool;

import java.util.Map;

/**
 * description: 格式化异常信息
 * create time at 2022/6/6 11:31
 *
 * @author alice.ruge
 * @since 0.0.3
 */

public class FormatTool {
    /**
     * 格式化异常信息
     *
     * @param e {@link Throwable}
     * @return 格式化异常信息
     */
    public static String buildJson(Throwable e) {
        if (e instanceof BaseBusinessException) {
            BaseBusinessException ex = (BaseBusinessException) e;
            if (StringTool.isNotBlank(ex.getExtMessage())) {
                return ex.getExtMessage();
            }
        }
        Map<Object, Object> build = MapTool.builder()
                .put("className", e.getStackTrace()[0].getClassName())
                .put("fileName", e.getStackTrace()[0].getFileName())
                .put("methodName", e.getStackTrace()[0].getMethodName())
                .put("lineNumber", e.getStackTrace()[0].getLineNumber())
                .build();
        return JsonTool.getObjToJson(build);
    }


    public static String buildJson(BaseBusinessException e) {
        IError error = e.getError();
        Response errorBody = new Response();
        errorBody.setStatus(Response.Status.FAILED);
        errorBody.setErrorCode(error.getErrorCode());
        errorBody.setErrorMessage(error.getErrorMessage());
        errorBody.setExtMessage(FormatTool.buildJson(e));
        return JsonTool.getObjToJson(errorBody);
    }
}
